package com.shopcart.service.impl;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyz.repository.CouponRepository;
import com.cyz.repository.UserCouponRepository;
import com.demo.dialet.PaginationSupport;
import com.demo.domain.Code;
import com.demo.mobile.MobException;
import com.demo.util.DateUtil;
import com.demo.util.JSONUtils;
import com.demo.util.MathUtil;
import com.demo.util.SqlUtils;
import com.demo.util.StringUtil;
import com.h5.Ret;
import com.shopcart.domain.Order;
import com.shopcart.domain.OrderDetail;
import com.shopcart.domain.PayLog;
import com.shopcart.domain.QuickShopping;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreGoods;
import com.shopcart.pay.acp.UpmpBase;
import com.shopcart.pay.wx.WxPrepay;
import com.shopcart.repository.OrderDetailRepository;
import com.shopcart.repository.OrderRepository;
import com.shopcart.repository.PayLogRepository;
import com.shopcart.service.OrderService;
import com.shopcart.service.QuickShoppingService;
import com.vsd.daoEx.model.OrderEx;
import com.vsd.domain.Coupon;
import com.vsd.domain.UserCoupon;
import com.vsd.mobile.error.MEnumError;
import com.vsd.repository.StoreGoodsRepository;
import com.vsd.service.CodeService;
import com.vsd.service.StoreService;
import com.zy.order.proto.MSOrder.MGoodsCart;
import com.zy.order.proto.MSOrder.MOrderList;
import com.zy.order.proto.MSOrder.MOrderMini;
import com.zy.sys.proto.MOCommon.MRet;
import com.zy.sys.proto.MOCommon.MRetEx;
import com.zy.sys.proto.MOCommon.MRetEx.Builder;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(OrderServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private UserCouponRepository userCouponRepository;
	@Autowired
	private CouponRepository couponRepository;
	@Autowired
	private StoreGoodsRepository storeGoodsRepository;
	@Autowired
	private StoreService storeService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private OrderDetailRepository orderDetailRepository; 
	@Autowired
	private PayLogRepository payLogRepository;
	@Autowired
	private QuickShoppingService quickShoppingService;
	
	@Override
	public int countByCreateTime(Date d) {
		// TODO Auto-generated method stub
		return orderRepository.countByCreateTimeAndState3(DateUtil.strToDate(DateUtil.dateToStr(d,"yyyy-MM-dd")+" 00:00:00", "yyyy-MM-dd HH:mm:ss"));
	}


	@Override
	public int selectGoodsSellCnt(String goodsId, String start, String end) {
		// TODO Auto-generated method stub
		String sql ="select count(1) from s_order o	left join s_order_detail d on "
			+ "o.id = d.order_id	where o.state=4 and d.goods_id= '"+goodsId+"' and o.create_time >= '"+start+"' and o.create_time <= '"+end+"'";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	@Override
	public Order findById(String id) {
		// TODO Auto-generated method stub
		return orderRepository.findOne(id);
	}
	
	@Override
	public void updateByPrimaryKey(Order order) {
		// TODO Auto-generated method stub
		orderRepository.save(order);
	}
	
	/**
	 * 生成菜品订单
	 */
	@Override
	public MRetEx.Builder postSingleOrder (
			com.zy.order.proto.MSOrder.MGoodsCartList.Builder carts,String userId) throws MobException{
		MRetEx.Builder ret = MRetEx.newBuilder();
		
		BigDecimal total = BigDecimal.ZERO;//订单实际总价
		BigDecimal totalWine = BigDecimal.ZERO;//酒水总价
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		String storeId = "";
		String couponInfo ="";
		List<OrderDetail> details = new ArrayList<OrderDetail>();
		String orderId = UUID.randomUUID().toString().replace("-", "");
		for (MGoodsCart cart : carts.getListList()) {
			StoreGoods g = storeGoodsRepository.findOne(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(StringUtils.isBlank(storeId)&&g.getType()!=2){
				storeId = g.getStoreId();
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}
			
			OrderDetail d = new OrderDetail();
			d.setId(StringUtil.getUUID());
			d.setGoodsId(g.getId());
			d.setGoodsImg(g.getImg());
			d.setGoodsName(g.getName());
			d.setGoodsType(g.getType());
			d.setNowPrice(g.getNowPrice());
			d.setNum(cart.getNum());
			d.setOrderId(orderId);
			d.setPrice(g.getNowPrice());
			d.setCreateTime(new Date());
			details.add(d);
		}
		
		Store store = storeService.findById(storeId);
		Integer wineRate = null;
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}else{
			wineRate = store.getWineRate();
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		//商家酒水不足
		if(wineDis.compareTo(store.getWineLeft())>0){
			wineDis = store.getWineLeft();
		}
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		total = total.add(winNeed);
		//生成订单
		Order order = new Order();
		
		if(StringUtils.isNotBlank(carts.getCouponId())){//优惠券
//			BigDecimal coupon = BigDecimal.ZERO;
			UserCoupon c = userCouponRepository.findOne(carts.getCouponId());
			if(c==null||c.getState()!=1) throw new MobException(MEnumError.COUPON_NOT_EXIST);
			Coupon co = couponRepository.findOne(c.getCouponId());
			if(co==null||DateUtil.compareDate(co.getBeginTime(), new Date())>0||DateUtil.compareDate(co.getEndTime(), new Date())<0){
				throw new MobException(MEnumError.COUPON_CAN_NOT_USE);
			}
			total = total.subtract(new BigDecimal(co.getValue()));
//			coupon = new BigDecimal(co.getValue());
			if(co.getType()==1){//满减
				couponInfo = "满"+total.toString()+"减"+co.getValue();
			}else{
				couponInfo = "现金券减免"+co.getValue();
			}
			order.setCashCoupon(new BigDecimal(co.getValue()));
			
			
			//优惠券设为 不可用状态
			c.setState(2);
			userCouponRepository.save(c);
		}
		
		
		order.setId(orderId);
		order.setBackState(1);
		order.setStoreCoupon(carts.getCouponId());
		order.setStoreCouponInfo(couponInfo);
		order.setCode(MathUtil.getRandomByTime(8));
		order.setCreateTime(new Date());
		order.setStoreId(store.getId());
		order.setIsShow(1);
		order.setModifyTime(new Date());
		order.setPayType(carts.getPaytype());
		order.setStoreName(store.getName());
		order.setStoreImg(store.getLogo());
		order.setPriceChange(BigDecimal.ZERO);
		order.setBackState(1);
		if (carts.getPaytype() == 1){//线上
			// 状态：未付款
			order.setState(1);
		}else {
			//状态：已付款
			order.setState(2);
			//线下付款  扣除商家酒水
			if(wineDis.compareTo(BigDecimal.ZERO)>0){
				store.setWineLeft(store.getWineLeft().subtract(wineDis));
				String sql = "update s_store set wine_left = " +store.getWineLeft().toString()+" where id = '"+store.getId()+"'";
				int c = jdbcTemplate.update(sql);
				if(c==0) throw new MobException(MEnumError.ORDER_CREATE_ERROR);
			}
			
		}
		order.setShowName(1);
		order.setInfo(carts.getInfo());
		order.setTotalPay(total);
		order.setUserId(userId);
		order.setHasComment(0);
		order.setWineMoney(wineDis);
		order.setType(1);
		
		Integer out = codeService.getOutTime();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, out);
		order.setPayDeadline(c.getTime());
		orderRepository.save(order);
		
		orderDetailRepository.save(details);
		
		ret.setCode("0");
		ret.setTitle(total.toString());
		ret.setMsg(orderId);
		return ret;
	}
	
	
	/**
	 * 生成团购订单
	 */
	@Override
	public MRetEx.Builder postTgOrder (
			com.zy.order.proto.MSOrder.MGoodsCartList.Builder carts,String userId) throws MobException{
		MRetEx.Builder ret = MRetEx.newBuilder();
		
		BigDecimal total = BigDecimal.ZERO;//订单实际总价
		String storeId = "";
		String couponInfo ="";
		List<OrderDetail> details = new ArrayList<OrderDetail>();
		String orderId = UUID.randomUUID().toString().replace("-", "");
		boolean quick = false;
		
		for (MGoodsCart cart : carts.getListList()) {
			StoreGoods g = storeGoodsRepository.findOne(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(g.getType()==3||g.getType()==1) throw new MobException(MEnumError.ONLY_TG_ALLOW);
			if(StringUtils.isBlank(storeId)){
				storeId = g.getStoreId();
			}
			BigDecimal nowPrice = g.getNowPrice();
			
			OrderDetail d = new OrderDetail();
			
			if(g.getMode() == 2){//抢购模式
				QuickShopping quickShopping = quickShoppingService.findById(cart.getId());
				if(quickShopping!=null && quickShopping.getState() == 3){
					nowPrice = new BigDecimal(quickShopping.getPrice());
					if(quickShopping.getTotal()<cart.getNum()){//数量不足
						throw new MobException(MEnumError.QUICK_GOODS_NOT_ENOUGH);
					}
					d.setInfo("限时抢购商品,时间段："+quickShopping.getBeginTime());
					//减少库存
					quickShopping.setTotal(quickShopping.getTotal()-cart.getNum());
					quickShoppingService.updateByPrimaryKey(quickShopping);
					quick = true;
				}
			}
			
			total = total.add(nowPrice.multiply(new BigDecimal(cart.getNum())));
			
			
			d.setId(StringUtil.getUUID());
			d.setGoodsId(g.getId());
			d.setGoodsImg(g.getImg());
			d.setGoodsName(g.getName());
			d.setGoodsType(g.getType());
			d.setNowPrice(nowPrice);
			d.setNum(cart.getNum());
			d.setOrderId(orderId);
			d.setPrice(g.getNowPrice());
			d.setCreateTime(new Date());
			details.add(d);
			
		}
		
		Store store = storeService.findById(storeId);
		
		//生成订单
		Order order = new Order();
		
		if(StringUtils.isNotBlank(carts.getCouponId())){//优惠券
			UserCoupon c = userCouponRepository.findOne(carts.getCouponId());
			if(c==null||c.getState()!=1) throw new MobException(MEnumError.COUPON_NOT_EXIST);
			Coupon co = couponRepository.findOne(c.getCouponId());
			if(co==null||DateUtil.compareDate(co.getBeginTime(), new Date())>0||DateUtil.compareDate(co.getEndTime(), new Date())<0){
				throw new MobException(MEnumError.COUPON_CAN_NOT_USE);
			}
			total = total.subtract(new BigDecimal(co.getValue()));
			if(co.getType()==1){//满减
				couponInfo = "满"+total.toString()+"减"+co.getValue();
			}else{
				couponInfo = "现金券减免"+co.getValue();
			}
			order.setCashCoupon(new BigDecimal(co.getValue()));
			
			
			//优惠券设为 不可用状态
			c.setState(2);
			userCouponRepository.save(c);
		}
		
		
		order.setId(orderId);
		order.setBackState(1);
		order.setStoreCoupon(carts.getCouponId());
		order.setStoreCouponInfo(couponInfo);
		order.setCode(MathUtil.getRandomByTime(8));
		order.setCreateTime(new Date());
		order.setStoreId(store.getId());
		order.setIsShow(1);
		order.setModifyTime(new Date());
		order.setPayType(carts.getPaytype());
		order.setStoreName(store.getName());
		order.setStoreImg(store.getLogo());
		order.setPriceChange(BigDecimal.ZERO);
		order.setBackState(1);
		if (carts.getPaytype() == 1){//线上
			// 状态：未付款
			order.setState(1);
		}else {
			//状态：已付款
//			order.setState(2);
			throw new MobException(MEnumError.TG_ORDER_ONLY_ONLINE);
		}
		order.setShowName(1);
		order.setInfo(carts.getInfo());
		order.setTotalPay(total);
		order.setUserId(userId);
		order.setHasComment(0);
		order.setWineMoney(BigDecimal.ZERO);
		order.setType(1);
		if(quick){//抢购模式 订单有效期
			Code hour = codeService.getByCode("1003");
			order.setPayDeadline(DateUtil.addHour(new Date(), Integer.parseInt(hour.getValue())));
		}
		
		orderRepository.save(order);
		
		orderDetailRepository.save(details);
		
		ret.setCode("0");
		ret.setTitle(total.toString());
		ret.setMsg(orderId);
		return ret;
	}

	@Override
	public MRet.Builder toPay(Integer type, String id,String cashId,String userId) throws MobException,Exception{
		MRet.Builder ret= MRet.newBuilder();
		
		Order order = orderRepository.findOne(id);
		if(order==null||order.getState()!=1){
			throw new MobException(MEnumError.ORDER_STATE_NOT_OK);
		}
		//在线支付额
		BigDecimal online = BigDecimal.ZERO;
		// 现金券总的抵扣
//		BigDecimal discount = BigDecimal.ZERO;
		
		// 使用现金券
		if (StringUtils.isNotBlank(cashId)) {
			UserCoupon uc = userCouponRepository.findOne(cashId);
			if(uc==null||uc.getState()!=1){
				throw new MobException(MEnumError.COUPON_NOT_FOUND);
			}
			Coupon coupon = couponRepository.findOne(uc.getCouponId());

			if (coupon == null) {
				throw new MobException(MEnumError.COUPON_NOT_FOUND);
			}

			if (coupon.getSource() != 1) {
				throw new MobException(MEnumError.COUPON_NOT_FOUND);
			}
			
//			if (coupon.getValue()!= null){
//				discount = new BigDecimal(coupon.getValue());
//			}
		}
		
		
		if(order.getPayDeadline()!=null && order.getPayDeadline().getTime() < new Date().getTime()){
			throw new MobException(MEnumError.ORDER_IS_USELESS);
		}
		
		online = order.getTotalPay();
		
		online = online.add(order.getPriceChange());//订单金额调整
		
		// 支付流水
		PayLog log = new PayLog();
		log.setCreateTime(new Date());
		log.setModifyTime(new Date());
		log.setMoney(online);
		log.setOrderId(order.getId());
		log.setSeller(order.getId());
		log.setState(0);
		log.setUserMoney(BigDecimal.ZERO);
		log.setCashId(cashId);
		log.setBuyer(userId);
		log.setId(StringUtil.getUUID());
		log = payLogRepository.save(log);
		
		/*********************************0311***************银联支付add***************************************/		
		if (online.floatValue() > 0){
			String tn = log.getId();
			if(type == 2){//银联支付
				tn = UpmpBase.upmpPurchase(online,  log.getId());
			}else if (type == 3) {
				tn = WxPrepay.wxPrepareId(online,  log.getId(), "购物车订单","8.8.8.8");
			}
			if(tn == null){
				throw new MobException(MEnumError.ORDER_CREATE_ERROR);
			}
		}
		/*********************************0311***************银联支付add***************************************/		
		ret.setCode(0);
		ret.setMsg(log.getId());
		return ret;
	}

	@Override
	public MOrderList.Builder selectMyOrderList(String userId,Integer state, Integer page, Integer limit)
			throws MobException {
		MOrderList.Builder ret = MOrderList.newBuilder();
//		String sql = "select * from (	select * from s_order o where o.user_id = "
//			+userId+"  order by o.create_time desc limit "
//			+ (page*limit)+","+limit+") d INNER JOIN  s_order_detail od on d.id = od.order_id";	
		String sql = "select *,(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 0,1) as gName1"
				+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as gNum1"
				+ ",(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 1,1) as gName2"
				+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 1,1)  as gNum2 "
				+ ",(select od2.goods_img from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as goodsImg "
				+ ",(select od2.goods_type from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as goodsType"
				+ ",(select sum(od.num) from s_order_detail od where od.order_id = o.id )  as totalNum "
				+ "from s_order o "
				+ "where o.state > 0 and  o.user_id = '"+userId+"'";
			if(state!=0){
				if(state==6){
					sql+=" and o.back_state >="+state;
				}else{
					sql+=" and o.state="+state+" and o.back_state=1";
				}
				
			}
			sql+= " order by o.create_time desc limit "+page*limit+","+limit;
			
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			MOrderMini.Builder m = MOrderMini.newBuilder();
			m.setCode(StringUtil.obj2String(map.get("code")));
			m.setId(StringUtil.obj2String(map.get("id")));
			m.setImg(StringUtil.obj2String(map.get("goodsImg")));
			if(map.get("pay_type")!=null) m.setPayType(new Integer(map.get("pay_type").toString()));
			if(map.get("state")!=null){
				if(!"1".equals(map.get("back_state").toString())){
					m.setState(new Integer(map.get("back_state").toString()));
				}else{
					m.setState(new Integer(map.get("state").toString()));
				}
			}
			m.setStoreId(StringUtil.obj2String(map.get("store_id")));
			m.setStoreName(StringUtil.obj2String(map.get("store_name")));
			m.setTime(DateUtil.dateAsOrder(StringUtil.obj2String(map.get("create_time"))));
			m.setTotal(map.get("totalNum")==null?0:new Integer(map.get("totalNum").toString()));
			if(StringUtils.isNotBlank(StringUtil.obj2String(map.get("price_change")))){
				m.setTotalPrice(new BigDecimal(map.get("total_pay").toString()).add(new BigDecimal(map.get("price_change").toString())).toString());
			}else{
				m.setTotalPrice(StringUtil.obj2String(map.get("total_pay")));
			}
			
			m.setType(map.get("goodsType")==null?1:new Integer(map.get("goodsType").toString()));
			//能否评价
			if(m.getState()==4&&"0".equals(StringUtil.obj2String(map.get("has_comment")))){//交易完成 且未评价
				m.setCanComment(1);
			}else{
				m.setCanComment(0);
			}
			MGoodsCart.Builder cart1 = MGoodsCart.newBuilder();
			cart1.setName(StringUtil.obj2String(map.get("gName1")));
			cart1.setNum(map.get("gNum1")==null?0:new Integer(map.get("gNum1").toString()));
			m.addCarts(cart1);
			if(map.get("gName2")!=null&&StringUtils.isNotBlank(map.get("gName2").toString())){
				MGoodsCart.Builder cart2 = MGoodsCart.newBuilder();
				cart2.setName(StringUtil.obj2String(map.get("gName2")));
				cart2.setNum(map.get("gNum2")==null?0:new Integer(map.get("gNum2").toString()));
				m.addCarts(cart2);
			}
			
			ret.addOrder(m);
		}
		
		return ret;
	}
	
	@Override
	public Collection<OrderDetail> selectDetails(String orderId){
		return orderDetailRepository.findByOrderId(orderId, new Sort(Direction.DESC, "id"));
	}


	@Override
	public List<OrderEx> selectExList(String areaCode, String storeId,
			String storeName, String beginTime, String endTime,Integer type) {
		String sql = "select o.*,u.nick_name as nickName,u.username,c.full,c.value as couponValue from s_order o "
				+ "left join f_user u on o.user_id = u.id "
				+ "left join s_store s on s.id = o.store_id "
				+ "left join f_user_coupon uc on uc.id = o.store_coupon "
				+ "left join f_coupon c on uc.coupon_id = c.id "
				+ "where 1=1 ";
		if(StringUtils.isNotBlank(areaCode)){
			sql+=" and s.area_code like '"+areaCode+"%'";
		}
		if(StringUtils.isNotBlank(storeId)){
			sql+=" and s.id = '"+storeId+"'";
		}
		if(StringUtils.isNotBlank(beginTime)){
			sql+=" and o.create_time >= '"+beginTime+"'";
		}
		if(StringUtils.isNotBlank(endTime)){
			sql+=" and o.create_time <= '"+endTime+"'";
		}
		if(StringUtils.isNotBlank(storeName)){
			sql+=" and s.name like '%"+storeName+"%'";
		}
		if(type!=null){
			sql+=" and o.type="+type;
		}
		sql+="order by o.create_time desc";
		
		if(PaginationSupport.getContext()!=null) sql = PaginationSupport.initPage(sql, jdbcTemplate);
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<OrderEx> exList = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			OrderEx ex = new OrderEx();
			SqlUtils.transMap2Bean2(map, ex);
			exList.add(ex);
		}
		return exList;
	}

	@Override
	public int updateByPrimaryKeySelective(Order order) {
		// TODO Auto-generated method stub
		try {
			String sql = SqlUtils.update(order, true, " where id = '"+order.getId()+"'");
			return jdbcTemplate.update(sql);
		}catch (Exception e) {
			// TODO Auto-generated catch block
			return 0;
		}
	}


	@Override
	public int storeAgreeBack(Order order, String storeId) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public int countByCreateTimeAndAreaCode(String areaCode, Date d) {
		// TODO Auto-generated method stub
		String sql = "select count(1) from s_order o left join s_store s "
				+ "where o.create_time >= '"+DateUtil.dateToStr(d, "yyyy-MM-dd HH:mm:ss")+"' and s.area_code like '"+areaCode+"%'";
		return jdbcTemplate.queryForObject(sql, Integer.class);
		
	}


	@Override
	public int countByCreateTimeAndStoreId(String storeId, Date d) {
		String sql = "select count(1) from s_order where store_id = '"+storeId+"' and create_time >= '"+DateUtil.dateToStr(d, "yyyy-MM-dd HH:mm:ss")+"'";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}
	@Override
	public Ret addDiancanOrder(String userId,Integer payType,String remark,String data,String couponId) throws Exception{
		JSONArray array = JSONArray.parseArray(data);
		BigDecimal total = BigDecimal.ZERO;//订单实际总价
		BigDecimal totalWine = BigDecimal.ZERO;//酒水总价
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		String storeId = "";
		String couponInfo ="";
		List<OrderDetail> details = new ArrayList<OrderDetail>();
		String orderId = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < array.size(); i++){
			JSONObject cart = array.getJSONObject(i);
			StoreGoods g = storeGoodsRepository.findOne(cart.getString("id"));
			if(g==null) return new Ret(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(StringUtils.isBlank(storeId)&&g.getType()==1){
				storeId = g.getStoreId();
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getInteger("num"))));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getInteger("num"))));
			}
			
			OrderDetail d = new OrderDetail();
			d.setId(StringUtil.getUUID());
			d.setGoodsId(g.getId());
			d.setGoodsImg(g.getImg());
			d.setGoodsName(g.getName());
			d.setGoodsType(g.getType());
			d.setNowPrice(g.getNowPrice());
			d.setNum(cart.getInteger("num"));
			d.setOrderId(orderId);
			d.setPrice(g.getNowPrice());
			d.setCreateTime(new Date());
			details.add(d);
		}
		
		Store store = storeService.findById(storeId);
		Integer wineRate = store.getWineRate();
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}
		
		//可减免酒水
		BigDecimal wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		if(wineDis.compareTo(store.getWineLeft())>0){
			wineDis = store.getWineLeft();
		}
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		total = total.add(winNeed);
		//生成订单
		Order order = new Order();
		
		if(StringUtils.isNotBlank(couponId)){//优惠券
//			BigDecimal coupon = BigDecimal.ZERO;
			UserCoupon c = userCouponRepository.findOne(couponId);
			if(c==null||c.getState()!=1) return new Ret(MEnumError.COUPON_NOT_EXIST);
			Coupon co = couponRepository.findOne(c.getCouponId());
			if(co==null||DateUtil.compareDate(co.getBeginTime(), new Date())>0||DateUtil.compareDate(co.getEndTime(), new Date())<0){
				return new Ret(MEnumError.COUPON_CAN_NOT_USE);
			}
			total = total.subtract(new BigDecimal(co.getValue()));
//			coupon = new BigDecimal(co.getValue());
			if(co.getType()==1){//满减
				couponInfo = "满"+total.toString()+"减"+co.getValue();
			}else{
				couponInfo = "现金券减免"+co.getValue();
			}
			order.setCashCoupon(new BigDecimal(co.getValue()));
			
			
			//优惠券设为 不可用状态
			c.setState(2);
			userCouponRepository.save(c);
		}
		
		order.setId(orderId);
		order.setBackState(1);
		order.setStoreCoupon(couponId);
		order.setStoreCouponInfo(couponInfo);
		order.setCode(MathUtil.getRandomByTime(8));
		order.setCreateTime(new Date());
		order.setStoreId(store.getId());
		order.setIsShow(1);
		order.setModifyTime(new Date());
		order.setPayType(payType);
		order.setStoreName(store.getName());
		order.setStoreImg(store.getLogo());
		order.setPriceChange(BigDecimal.ZERO);
		order.setBackState(1);
		if (payType == 1){//线上
			// 状态：未付款
			order.setState(1);
		}else {
			//状态：已付款
			order.setState(2);
			//线下付款  扣除商家酒水
			if(wineDis.compareTo(BigDecimal.ZERO)>0){
				store.setWineLeft(store.getWineLeft().subtract(wineDis));
				String sql = "update s_store set wine_left = " +store.getWineLeft().toString()+" where id = '"+store.getId()+"'";
				int c = jdbcTemplate.update(sql);
				if(c==0) throw new MobException(MEnumError.ORDER_CREATE_ERROR);
			}
		}
		order.setShowName(1);
		order.setInfo(remark);
		order.setTotalPay(total);
		order.setUserId(userId);
		order.setHasComment(0);
		order.setWineMoney(wineDis);
		order.setType(1);
		
		Integer out = codeService.getOutTime();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, out);
		order.setPayDeadline(c.getTime());
		orderRepository.save(order);
		
		orderDetailRepository.save(details);
		
		
		Ret ret = new Ret(0);
		JSONObject r = new JSONObject();
		r.put("title", total.toString());
		r.put("msg", orderId);
		ret.setData(r);
		return ret;
	}
	
	@Override
	public String selectMyOrders(String userId, Integer page, Integer limit,Integer state)
			{
		
//		String sql = "select * from (	select * from s_order o where o.user_id = "
//			+userId+"  order by o.create_time desc limit "
//			+ (page*limit)+","+limit+") d INNER JOIN  s_order_detail od on d.id = od.order_id";	
		String sql = "";
		if (state == null || state == 0){
			sql = "select *,(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 0,1) as gName1"
					+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as gNum1"
					+ ",(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 1,1) as gName2"
					+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 1,1)  as gNum2 "
					+ ",(select od2.goods_img from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as goodsImg "
					+ ",(select sum(od.num) from s_order_detail od where od.order_id = o.id )  as totalNum "
					+ "from s_order o "
					+ "where o.user_id = '"+userId+"' order by o.create_time desc limit "+page*limit+","+limit;
		}else {
			sql = "select *,(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 0,1) as gName1"
					+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as gNum1"
					+ ",(select od1.goods_name from s_order_detail  od1 where  od1.order_id = o.id order by od1.id desc limit 1,1) as gName2"
					+ ",(select od2.num from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 1,1)  as gNum2 "
					+ ",(select od2.goods_img from s_order_detail  od2 where  od2.order_id = o.id order by od2.id desc limit 0,1)  as goodsImg "
					+ ",(select sum(od.num) from s_order_detail od where od.order_id = o.id )  as totalNum "
					+ "from s_order o "
					+ "where o.user_id = '"+userId+"' and o.state = "+state+" order by o.create_time desc limit "+page*limit+","+limit;
		}
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		JSONArray ret = new JSONArray();
		for (Map<String, Object> map : maps) {
			JSONObject object = new JSONObject();
			JSONArray carts = new JSONArray();
			object.put("code", StringUtil.obj2String(map.get("code")));
			object.put("id", StringUtil.obj2String(map.get("id")));
			object.put("img", StringUtil.obj2String(map.get("goodsImg")));
			object.put("id", StringUtil.obj2String(map.get("id")));
			object.put("id", StringUtil.obj2String(map.get("id")));
			if(map.get("pay_type")!=null) {
				object.put("payType", new Integer(map.get("pay_type").toString()));
			}
			if(map.get("state")!=null) {
				object.put("state", new Integer(map.get("state").toString()));
			}
			object.put("storeId", StringUtil.obj2String(map.get("store_id")));
			object.put("storeName", StringUtil.obj2String(map.get("store_name")));
			object.put("time", DateUtil.dateAsQQ(StringUtil.obj2String(map.get("create_time"))));
			object.put("total", map.get("totalNum")==null?0:new Integer(map.get("totalNum").toString()));
			object.put("totalPrice", StringUtil.obj2String(map.get("total_pay")));
			object.put("type", map.get("type")==null?1:new Integer(map.get("type").toString()));
			JSONObject carto = new JSONObject();
			carto.put("name", StringUtil.obj2String(map.get("gName1")));
			carto.put("num", map.get("gNum1")==null?0:new Integer(map.get("gNum1").toString()));
			carts.add(carto);
			if(map.get("gName2")!=null&&StringUtils.isNotBlank(map.get("gName2").toString())){
				JSONObject carto2 = new JSONObject();
				carto2.put("name", StringUtil.obj2String(map.get("gName2")));
				carto2.put("num", map.get("gNum1")==null?0:new Integer(map.get("gNum2").toString()));
				carts.add(carto2);
			}
			object.put("carts", carts);
			ret.add(object);
		}
		
		return JSONUtils.serialize(ret);
	}


	/**
	 * 生成菜品订单
	 */
	@Override
	public MRetEx.Builder postPadOrder (
			com.zy.order.proto.MSOrder.MGoodsCartList.Builder carts,String storeId) throws MobException{
		MRetEx.Builder ret = MRetEx.newBuilder();
		
		BigDecimal total = BigDecimal.ZERO;//订单实际总价
		BigDecimal totalWine = BigDecimal.ZERO;//酒水总价
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		String couponInfo ="";
		List<OrderDetail> details = new ArrayList<OrderDetail>();
		String orderId = UUID.randomUUID().toString().replace("-", "");
		for (MGoodsCart cart : carts.getListList()) {
			StoreGoods g = storeGoodsRepository.findOne(cart.getId());
			if(g==null) throw new MobException(MEnumError.ORDER_GOODS_NOT_EXIST);
			if(g.getType()==2){
				throw new MobException(MEnumError.ONLY_DISH_ALLOW);
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getNum())));
			}
			
			OrderDetail d = new OrderDetail();
			d.setId(StringUtil.getUUID());
			d.setGoodsId(g.getId());
			d.setGoodsImg(g.getImg());
			d.setGoodsName(g.getName());
			d.setGoodsType(g.getType());
			d.setNowPrice(g.getNowPrice());
			d.setNum(cart.getNum());
			d.setOrderId(orderId);
			d.setPrice(g.getNowPrice());
			d.setCreateTime(new Date());
			details.add(d);
		}
		
		Store store = storeService.findById(storeId);
		Integer wineRate = null;
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}else{
			wineRate = store.getWineRate();
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		if(wineDis.compareTo(store.getWineLeft())>0){
			wineDis = store.getWineLeft();
		}
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		total = total.add(winNeed);
		//生成订单
		Order order = new Order();
//		
//		if(StringUtils.isNotBlank(carts.getCouponId())){//优惠券
////			BigDecimal coupon = BigDecimal.ZERO;
//			UserCoupon c = userCouponRepository.findOne(carts.getCouponId());
//			if(c==null||c.getState()!=1) throw new MobException(MEnumError.COUPON_NOT_EXIST);
//			Coupon co = couponRepository.findOne(c.getCouponId());
//			if(co==null||DateUtil.compareDate(co.getBeginTime(), new Date())>0||DateUtil.compareDate(co.getEndTime(), new Date())<0){
//				throw new MobException(MEnumError.COUPON_CAN_NOT_USE);
//			}
//			total = total.subtract(new BigDecimal(co.getValue()));
////			coupon = new BigDecimal(co.getValue());
//			if(co.getType()==1){//满减
//				couponInfo = "满"+total.toString()+"减"+co.getValue();
//			}else{
//				couponInfo = "现金券减免"+co.getValue();
//			}
//			order.setCashCoupon(new BigDecimal(co.getValue()));
//			
//			
//			//优惠券设为 不可用状态
//			c.setState(2);
//			userCouponRepository.save(c);
//		}
//		
		order.setId(orderId);
		order.setBackState(1);
		order.setStoreCoupon(carts.getCouponId());
		order.setStoreCouponInfo(couponInfo);
		order.setCode(MathUtil.getRandomByTime(8));
		order.setCreateTime(new Date());
		order.setStoreId(store.getId());
		order.setIsShow(1);
		order.setModifyTime(new Date());
		order.setPayType(carts.getPaytype());
		order.setStoreName(store.getName());
		order.setStoreImg(store.getLogo());
		order.setPriceChange(BigDecimal.ZERO);
		order.setBackState(1);
		if (carts.getPaytype() == 1){//线上
			// 状态：未付款
			order.setState(1);
		}else {
			//状态：已付款
			order.setState(2);
		}
		order.setShowName(1);
		order.setInfo(carts.getInfo());
		order.setTotalPay(total);
		order.setUserId("-1");//系统默认用户
		order.setHasComment(0);
		order.setWineMoney(wineDis);
		order.setType(1);
		
		Integer out = codeService.getOutTime();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, out);
		order.setPayDeadline(c.getTime());
		orderRepository.save(order);
		
		orderDetailRepository.save(details);
		
		ret.setCode("0");
		ret.setTitle(total.toString());
		ret.setMsg(orderId);
		return ret;
	}

 
	
}
